/*
*  Copyright 2019-2020
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.qp.basics.admin.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.qp.basics.admin.repository.LinkIconRepository;
import com.qp.basics.admin.service.LinkIconService;
import com.qp.basics.admin.service.dto.LinkIconQueryCriteria;
import com.qp.basics.common.domain.LinkIcon;
import com.qp.basics.common.poi.ExcelX;
import com.qp.basics.common.service.dto.LinkIconDto;
import com.qp.basics.common.service.mapstruct.LinkIconMapper;
import com.qp.basics.common.utils.*;

import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
*
* @description 服务实现
**/
@Service
@RequiredArgsConstructor
public class LinkIconServiceImpl implements LinkIconService {

    private final LinkIconRepository linkIconRepository;
    private final LinkIconMapper linkIconMapper;

    @Override
    public Map<String,Object> queryAll(LinkIconQueryCriteria criteria, Pageable pageable){
        Page<LinkIcon> page = linkIconRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(linkIconMapper::toDto));
    }

    @Override
    public List<LinkIconDto> queryAll(LinkIconQueryCriteria criteria){
        return linkIconMapper.toDto(linkIconRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public LinkIconDto findById(Long id) {
        LinkIcon linkIcon = linkIconRepository.findById(id).orElseGet(LinkIcon::new);
        ValidationUtil.isNull(linkIcon.getId(),"LinkIcon","id",id);
        return linkIconMapper.toDto(linkIcon);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LinkIconDto create(LinkIcon resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId());
        return linkIconMapper.toDto(linkIconRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(LinkIcon resources) {
        LinkIcon linkIcon = linkIconRepository.findById(resources.getId()).orElseGet(LinkIcon::new);
        ValidationUtil.isNull( linkIcon.getId(),"LinkIcon","id",resources.getId());
        resources.setId(linkIcon.getId());
        linkIconRepository.save(resources);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            linkIconRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<LinkIconDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (LinkIconDto linkIcon : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("位置", linkIcon.getPosition());
            map.put("标题", linkIcon.getTitle());
            map.put("地址", linkIcon.getUrl());
            map.put("图片地址", linkIcon.getPic());
            map.put("链接类型", linkIcon.getLinkType());
            map.put("顺序号", linkIcon.getSnum());
            map.put("备注", linkIcon.getRemark());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public JSONObject importExcel(MultipartFile file) {
        JSONObject res=new JSONObject();

        try (InputStream is = file.getInputStream()) {
            ExcelX ex = new ExcelX(is);
            List<Map> l = ex.excelToMapList(0);
            int count=0;
            for (int i = 0; i < l.size(); i++) {
                Map m = l.get(i);
                Object t = m.get("id");
                if (t == null || "".equals(t)) {
                    continue;
                }
                LinkIcon q = new LinkIcon();
            String position = ImortExportUtil.toStr(m.get("位置"));
            q.setPosition(position);
            String title = ImortExportUtil.toStr(m.get("标题"));
            q.setTitle(title);
            String url = ImortExportUtil.toStr(m.get("地址"));
            q.setUrl(url);
            String pic = ImortExportUtil.toStr(m.get("图片地址"));
            q.setPic(pic);
            String linkType = ImortExportUtil.toStr(m.get("链接类型"));
            q.setLinkType(linkType);
            String snum = ImortExportUtil.toStr(m.get("顺序号"));
            //q.setSnum(snum);
            String remark = ImortExportUtil.toStr(m.get("备注"));
            q.setRemark(remark);
                q = linkIconRepository.save(q);
                count++;
            }
            res.put("msg","导入成功：共导入"+count+"条");
        } catch (IOException e) {
            e.printStackTrace();
            res.put("msg","导入失败："+e.getMessage());
        }
        return res;
    }
}
